package net.csdn.business.gateway.component;

import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.constant.GatewayConstants;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: zhangyalei
 * @Date: 2022/12/22 10:41
 * @Description: 自定义限流器
 */
@Slf4j
@Component
public class CustomRedisRateLimiter {


    private final String keyNamespace= GatewayConstants.RATE_LIMIE_NAME_SPACE_S;

    private final RedisTemplate<String, Long> redisTemplate;

    private final RedisScript<List<Long>> redisScript;

    /**
     * @param redisScript 该RedisScript对象将会自动注入进来，该对象使用的spring-cloud-gateway-core.jar包的META-INF/scripts/request-rate-limiter.lua路径脚本
     */
    public CustomRedisRateLimiter(RedisTemplate redisTemplate,
                              RedisScript<List<Long>> redisScript){
        this.redisTemplate = redisTemplate;
        this.redisScript = redisScript;
    }

    public boolean isAllowed(String key, int replenishRate, int burstCapacity){
        List<String> keys = Arrays.asList(keyNamespace+key+"tokens", keyNamespace+key+"timestamp");
        try {
            List<Long> response = this.redisTemplate.execute(this.redisScript, keys,
                    replenishRate,
                    burstCapacity,
                    "",
                    1);
            if(response.get(0) ==0){
                return false;
            }else{
                return true;
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return true;
        }

    }

}
